package com.subfg.common.util.common;

import com.subfg.common.entity.excpetion.BusinessExceptionModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    private static Logger log = LoggerFactory.getLogger(StringUtil.class);

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 空字符串
     */
    private static final String NULLSTR = "";
    /**
     * 邮箱账户
     */
    public static final String Email_REG = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";

    private static final String[] fileTypeList = {".png", ".jpg", ".jpeg"};

    /**
     * 随机生成6位验证码
     * @return
     */
    public static String verifyCode(){
        String str = "1234567890";
        char[] code = new char[6];
        int length = code.length;
        for(int i = 0; i < length; i++){
            int rand = (int)(Math.random()*9);
            code[i] =str.charAt(rand);
        }
        return String.valueOf(code);
    }

    //密码盐
    public static String verifySalt(){
        String str = "1234567890qwertyuiopasdfghjklzxcvbnm";
        char[] code = new char[6];
        int length = code.length;
        for(int i = 0; i < length; i++){
            int rand = (int)(Math.random()*35);
            code[i] =str.charAt(rand);
        }
        return String.valueOf(code);
    }

    public static boolean verifyEmailLegal(String email, List<String> strList) throws BusinessExceptionModel {
        if (StringUtil.isEmpty(email) || !StringUtil.isEmail(email)) {
            throw new BusinessExceptionModel();
        }
        String suffixEmail = email.split("@")[1].toLowerCase(Locale.ROOT);
        for (String str : strList) {
            if (str.equals(suffixEmail)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 随机生成用户名
     */
    public static String randomName(){
        return "user"+verifyCode();
    }


    /**
     * 邮箱验证
     * @param email
     *  false 不是邮箱   true 是邮箱
     * @return
     */
    public static boolean isEmail(String email){
        Pattern pattern = Pattern.compile(Email_REG);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * 验证文件后缀是否符合后台规则
     * @param filePathSuffix        文件后缀
     * @return
     */
    public static boolean isFileType(String filePathSuffix) {
        if (isEmpty(filePathSuffix)) {
            return false;
        }
        String fileSuffix = filePathSuffix.substring(filePathSuffix.lastIndexOf("."));
        String headSubffix = filePathSuffix.substring(0, 4);
        if (isEmpty(fileSuffix)) {
            return true;
        }
        if (headSubffix.equals("http")) {
            return true;
        }
        for (String suffix : fileTypeList) {
            if (fileSuffix.equals(suffix)) {
                return false;
            }
        }
        return true;
    }



    /**
     * 去空格
     */
    public static String trim(String str) {
        return (str == null ? "" : str.trim());
    }


    /**
     * * 判断一个对象是否非空
     * @param object Object
     * @return true：非空 false：空
     */
    public static boolean isNotNull(Object object) {
        return !isNull(object);
    }



    /**
     * * 判断一个对象是否为空
     * @param object Object
     * @return true：为空 false：非空
     */
    public static boolean isNull(Object object) {
        return object == null;
    }



    /**
     * 截取字符串
     *
     * @param str 字符串
     * @param start 开始
     * @param end 结束
     * @return 结果
     */
    public static String substring(final String str, int start, int end) {
        if (str == null) {
            return NULLSTR;
        }

        if (end < 0) {
            end = str.length() + end;
        }
        if (start < 0) {
            start = str.length() + start;
        }

        if (end > str.length()) {
            end = str.length();
        }

        if (start > end) {
            return NULLSTR;
        }

        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }

        return str.substring(start, end);
    }

    /**
     * * 判断一个字符串是否为非空串
     *
     * @param str String
     * @return true：非空串 false：空串
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * * 判断一个字符串是否为空串
     *
     * @param str String
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(String str) {
        return isNull(str) || NULLSTR.equals(str.trim());
    }


    /**
     * 去除 换行符、制表符
     * @param str
     * @return
     */
    public static String replace(String str) {
        if (str.length() != 0) {
            return str.replaceAll("\r|\n", "");
        }
        return str;
    }

    /**
     * 获取字符尾部字符, 转为int
     * @param str
     * @return
     */
    public static String getStringEnd(String str) {
        Integer length = str.length() - 1;
        Integer endNumber = Integer.valueOf(str.substring(length));
        String substring = str.substring(0, length);
        String orderNo = substring+(endNumber+1);
        return orderNo;
    }


    /**
     *  获取json文件, 返回json文件中的字符
     * @param Filename
     * @return
     */
    public static String readJsonFile(String Filename) {
        String jsonStr = "";
        try {
            File jsonFile = new File(Filename);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 验证账号类型
     */
    public static Integer AccountType(String account){
        Integer num = null;
        if(StringUtil.isEmail(account)){
            //邮箱判断
            num = 1;
        }else{
            num = 2;
        }
        return num;
    }

    /**
     * 利用反射获取类的所有属性值
     * @param object
     * @return
     */
    public static List<String> getClassValues(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        List<String> listStr = new ArrayList<>();
        for (Field field: fields) {
            try {
                listStr.add((String) field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return listStr;
    }

    /**
     *  unicode转utf-8
     */
    public static String decodeUnicode(String unicodeStr) {
        char aChar;
        int len = unicodeStr.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = unicodeStr.charAt(x++);
            if (aChar == '\\') {
                aChar = unicodeStr.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = unicodeStr.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                return "";
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     *  文件内容, classPath 下的
     */
    public static String getFileContents(String filePath) {
        log.info("读取==>>{}文件内容", filePath);
        Resource resource = new ClassPathResource(filePath);
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = null;
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            log.error("读取{}内容失败", filePath);
            e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 替换内容
     * @param original
     * @param replace
     * @param replaceContent
     * @return
     */
    public static String replaceStr(String original, String replace, String replaceContent) {
        if (!StringUtil.isEmpty(original) && !StringUtil.isEmpty(replace) && !StringUtil.isEmpty(replaceContent)) {
            return original.replace(replace, replaceContent);
        }
        return null;
    }
}
